package com.ato.Exception;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author wangjing
 * @create 2021--09--07--21:34
 */
public class ExceptionStudy {
    public static void main(String[] args) {
        ExceptionTest ext = new ExceptionTest();
        int i = ext.tryTest();
        System.out.println(i);
        ThrowsTest throwsTest = new ThrowsTest();
        try {
            throwsTest.generateException(-1);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}

class ExceptionTest {
    public int tryTest() {
        try {
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        } catch (Exception e) {
            System.out.println("catch 可以有多个2：" + e.getMessage());
//            e.printStackTrace();
            return 2;
        } finally {
            System.out.println("即使有异常，处理后，finally里的代码一定会被执行");
        }
    }
}

class ExceptionTest2 {
    @Test
    public void testFile() {
        FileInputStream fileInputStream = null;
        try {
            File file = new File("hello world");
            fileInputStream = new FileInputStream(file);
            int data = fileInputStream.read();
            for (int i = 0; i < data; i++) {
                data = fileInputStream.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) // 加上判断是因为：fileInputStream 在创建时就可能是null  那么 null再去close 就会是空指针异常
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class ThrowsTest {

    @Test
    public void test1() {
//        注意这里也可以在往上抛异常 ： 有点像koa的洋葱圈，感觉
        try {
            testFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test

    public void testFile() throws FileNotFoundException, IOException {

        File file = new File("hello world");
        FileInputStream fileInputStream = new FileInputStream(file);
        int data = fileInputStream.read();
        for (int i = 0; i < data; i++) {
            data = fileInputStream.read();
        }
        fileInputStream.close();
    }

    public void generateException(int i) throws Exception {
        if (i > 0) {
            System.out.println("正确输入");
        } else {
            throw new Exception("参数输入异常");

        }
    }

}

/**
 * 需要继承 ：RuntimeException 或者   Exception
 * 提供 serialVersionUID  long类型就行 用于标识
 * 提供有参和无参构造器
 */
class CustomException extends Exception {
    static final long serialVersionUID = -3387516993124229948L;

    public CustomException() {
    }

    public CustomException(String message) {
        super(message);
    }
}